package com.ljh.lottery.common.advice;

import com.ljh.lottery.common.errorcode.ErrorCode;
import com.ljh.lottery.common.errorcode.GlobalErrorCodeConstants;
import com.ljh.lottery.common.exception.ControllerException;
import com.ljh.lottery.common.exception.ServiceException;
import com.ljh.lottery.pojo.response.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.HandlerMethodValidationException;

/**
 * @author: Themberfue
 * @date: 2025/4/8 12:37
 * @description:
 */
@ResponseBody
@ControllerAdvice
public class ExceptionAdvice {
    private static final Logger log = LoggerFactory.getLogger(ExceptionAdvice.class);

    @ExceptionHandler
    public CommonResult<?> exceptionHandler(Exception e) {
        log.error("发生异常，e：", e);
        return CommonResult.fail(GlobalErrorCodeConstants.UNKNOWN);
    }

    @ExceptionHandler
    public CommonResult<?> exceptionHandler(ControllerException e) {
        log.error("发生异常, e:", e);
        return CommonResult.fail(
                new ErrorCode(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), e.getMessage()));
    }

    @ExceptionHandler
    public CommonResult<?> exceptionHandler(ServiceException e) {
        log.error("发生异常, e:", e);
        return CommonResult.fail(
                new ErrorCode(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), e.getMessage()));
    }

    @ExceptionHandler
    public CommonResult<?> exceptionHandler(HandlerMethodValidationException e) {
        log.error("发生异常，e：{}", e.getMessage());
        return CommonResult.fail(GlobalErrorCodeConstants.CLIENT_ERROR.getCode(), "参数校验不正确");
    }

    @ExceptionHandler
    public CommonResult<?> exceptionHandler(MethodArgumentNotValidException e) {
        String msg = e.getBindingResult().getFieldError().getDefaultMessage();
        log.error("发生异常, e: {}", e.getMessage());
        return CommonResult.fail(
                new ErrorCode(GlobalErrorCodeConstants.CLIENT_ERROR.getCode(), msg));
    }
}
